<?php

class Core_Component_System_Business_Dms_Entity {
    
    public function createEntityFile($entity){
        $beforeInsert = '';
        if($entity->getIsVersion()){
            $beforeInsert .= "\n\t\t$"."this->setWebsiteId(App::getRunningWebsite()->getId());";
        }
        if($entity->getIsCreator()){
            $beforeInsert .= "\n\t\t$"."this->setCreator($"."GLOBALS[RC]->getIdentity()->getName());";
        }
        if($entity->getIsUpdator()){
            $beforeInsert .= "\n\t\t$"."this->setUpdator($"."GLOBALS[RC]->getIdentity()->getName());";
        }
        if($entity->getIsCreatedTime()){
            $beforeInsert .= "\n\t\t$"."this->setCreatedTime(Soul_Util_Date::dbNow());";
        }
        if(!empty($beforeInsert)){
            $beforeInsert = "\n\n\tprotected function beforeInsert(){".$beforeInsert."\n\t\tparent::beforeInsert();\n\t}";
        }

        $beforeUpdate = '';
        if($entity->getIsUpdator()){
            $beforeUpdate .= "\n\t\t$"."this->setUpdator($"."GLOBALS[RC]->getIdentity()->getName());";
        }        
        if(!empty($beforeUpdate)){
            $beforeUpdate = "\n\n\tprotected function beforeUpdate(){".$beforeUpdate."\n\t\tparent::beforeUpdate();\n\t}";
        }        
        
        $code = '<?php'
              . "\nclass Core_".$entity->getClassName()
              . ' extends '.($entity->getIsVersion()? 'Core_Model_Entity_Dynamic_Version': 'Core_Model_Entity_Dynamic_Base')
              . "{"
              . "\n\n\tprotected $"."tableName = '{t}".$entity->getEntityTableName()."';"
              . $beforeInsert
              . $beforeUpdate
              . "\n\n}";
        $filename = DP_CODE.'Core'.DS.str_replace('_', DS, $entity->getClassName()).'.php';
        Soul_Util_FS::writeFile($code, $filename);   
    }
    
    public function createEntityTable($entity){
        $db = $GLOBALS[RC]->getDb();
        $db->setSql('DROP TABLE IF EXISTS `{t}'.$entity->getEntityTableName().'`')->execute();
        $sql = 'CREATE TABLE `'.$entity->getEntityTableName().'` (
          `id` int(11) NOT NULL AUTO_INCREMENT,
          PRIMARY KEY (`id`)
        )';
        $db->setSql($sql)->execute();
        
        if($entity->getIsVersion()){
            $db->setSql('DROP TABLE IF EXISTS `{t}'.$entity->getEntityTableName().'_version`')->execute();
            $sql = 'CREATE TABLE `'.$entity->getEntityTableName().'_version` (
              `version_id` int(11) NOT NULL AUTO_INCREMENT,
              `main_id` int(11) NOT NULL,
              PRIMARY KEY (`version_id`)
            )';
            $db->setSql($sql)->execute();
        }
        
        App::getModel('system/dms_property')
            ->setEntityId($entity->getId())
            ->setName('id')
            ->setPropertyType('integer')
            ->setFieldType('int')
            ->setRequired(TRUE)
            ->setInputType(NULL)
            ->setIsPrimary(TRUE)
            ->setIsIncrement(TRUE)
            ->setVersionable(FALSE)
            ->save();
        
        App::getModel('system/dms_property')
            ->setEntityId($entity->getId())
            ->setName('website_id')
            ->setPropertyType('integer')
            ->setFieldType('int')
            ->setRequired(TRUE)
            ->setInputType(NULL)
            ->setInsertable(TRUE)
            ->setUpdateable(FALSE)
            ->setVersionable($entity->getIsVersion())
            ->save();            
        
        if($entity->getIsCreator()){
            App::getModel('system/dms_property')
                ->setEntityId($entity->getId())
                ->setName('creator')
                ->setPropertyType('string')
                ->setFieldType('varchar')
                ->setRequired(TRUE)
                ->setUpdateable(FALSE)
                ->setInsertable(TRUE)
                ->setInputType(NULL)
                ->setLength(50)
                ->setVersionable($entity->getIsVersion())
                ->setLabel('system.label.creator')
                ->save();
        }
        
        if($entity->getIsUpdator()){
            App::getModel('system/dms_property')
                    ->setEntityId($entity->getId())
                    ->setName('updator')
                    ->setPropertyType('string')
                    ->setFieldType('varchar')
                    ->setRequired(TRUE)
                    ->setInsertable(TRUE)
                    ->setUpdateable(TRUE)
                    ->setInputType(NULL)
                    ->setLength(50)
                    ->setVersionable($entity->getIsVersion())
                    ->setLabel('system.label.updator')
                    ->save();
        }        
        
        if($entity->getIsCreatedTime()){
            App::getModel('system/dms_property')
                    ->setEntityId($entity->getId())
                    ->setName('created_time')
                    ->setPropertyType('timestamp')
                    ->setFieldType('timestamp')
                    ->setRequired(TRUE)
                    ->setInsertable(TRUE)
                    ->setUpdateable(FALSE)
                    ->setInputType(NULL)
                    ->setVersionable($entity->getIsVersion())
                    ->setLabel('system.label.created_time')
                    ->save();
        }

        if($entity->getIsUpdatedTime()){
            App::getModel('system/dms_property')
                    ->setEntityId($entity->getId())
                    ->setName('updated_time')
                    ->setPropertyType('timestamp')
                    ->setFieldType('timestamp')
                    ->setRequired(TRUE)
                    ->setInsertable(FALSE)
                    ->setUpdateable(FALSE)
                    ->setTimestampAction('auto_update_time')
                    ->setLabel('system.label.updated_time')
                    ->setVersionable($entity->getIsVersion())
                    ->setInputType(NULL)
                    ->save();        
        }
    }

    public function createField($property){
        $db = $GLOBALS[RC]->getDb();
        $model = $property->getEntity()->createModelInstance();
        $tableName = $property->getVersionable()? $model->getVersionTableName(): $model->getTableName();
        $sql= 'Describe `'.$tableName.'` `'.$property->getName().'`';
        if(!$db->setSql($sql)->fetch()->getFirstValue()){
            $sql = 'ALTER TABLE `'.$tableName.'` ADD `'.$property->getName().'` '. $property->getFieldType();
            if($property->issetData('length')){
                $sql .= '('.$property->getLength().')';
            }
            if($property->getRequired()){
                $sql .= ' NOT NULL';
            }
            if($property->getPropertyType() == 'timestamp'){
                if($property->getTimestampAction() == 'auto_update_time'){
                    $sql .= " DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP";
                }else{
                    $sql .= " DEFAULT '0000-00-00 00:00:00'";
                }
            }else{
                if($property->getDefaultValue()){
                    $sql .= " DEFAULT '".$property->getDefaultValue()."'";
                }
            }
            $db->setSql($sql)->execute();
        }
    }    
    
    public function removeField($property){
        $db = $GLOBALS[RC]->getDb();
        $model = $property->getEntity()->createModelInstance();
        $tableName = $property->getVersionable()? $model->getVersionTableName(): $model->getTableName();
        $sql= 'Describe `'.$tableName.'` `'.$property->getName().'`';
        if($db->setSql($sql)->fetch()->getFirstValue()){
            $sql = 'ALTER TABLE `'.$tableName.'` DROP `'.$property->getName().'`';
            $db->setSql($sql)->execute();
        }
    }
    
    public function changeVersionField($property){
        $property->setVersionable(TRUE);
        $this->createField($property);
        
        $model = $property->getEntity()->createModelInstance();
        $id1 = $model->getIdProperty()->getName();
        $id2 = $model->getVersionRelationProperty()->getName();
        
        $sql = 'UPDATE `'.$model->getTableName().'` AS `a`, `'.$model->getVersionTableName().'` AS `b`'
             . ' SET `b`.`'.$property->getName().'`=`a`.`'.$property->getName().'`'
             . ' WHERE `a`.`'.$id1.'`=`b`.`'.$id2.'`';
        $GLOBALS[RC]->getDb()->setSql($sql)->execute();

        $property->setVersionable(FALSE);
        $this->removeField($property);
        
        $sql = 'UPDATE `{t}system_dms_property` SET `versionable`=1 WHERE `id`='.$property->getId().'';
        $GLOBALS[RC]->getDb()->setSql($sql)->execute();
    }    
}